package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.model.utils.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
@Slf4j
public class UserService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * description: 上传用户头像 <br>
     * version: 1.0 <br>
     * date: 2021/11/14 20:18 <br>
     * author: SangWu <br>
     *
     * @param headPhoto
     * @return void
     */
    public void uploadHead(MultipartFile headPhoto) throws IOException {
        String originalFilename = headPhoto.getOriginalFilename();
        InputStream inputStream = headPhoto.getInputStream();
        String retUrl = ossTemplate.upload(originalFilename, inputStream);
        //
        boolean detect = aipFaceTemplate.detect(retUrl);
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }
        log.info("人脸识别成功");
        UserInfo userInfo = new UserInfo();
        Long userId = UserHolder.getUserId();
        userInfo.setAvatar(retUrl);
        userInfo.setId(userId);
        userInfoApi.update(userInfo);
    }

    public UserInfoVo getUserInfoById(Long userID) {
        if (userID == null) {
            userID = UserHolder.get().getId();
        }
        UserInfo userInfo = userInfoApi.findById(userID);
        //
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);

        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    public void updateUserInfoById(UserInfo userInfo) {
        Long userId = UserHolder.getUserId();
        userInfo.setId(userId);
        userInfoApi.update(userInfo);
    }
}
